<template>
  <div class="app-container" :style="'height:' + height + 'px'">
    <el-row style="height: 100%">
      <el-col :span="16">
        <div style="width: 100%; height: 100%" v-html="poHtmlCode"></div>
      </el-col>
      <el-col :span="8" style="padding-right: 20px;">
        <input type="hidden" name="templateCode" id="templateCode" />
        <input type="hidden" name="templateName" id="templateName" />
        <input type="hidden" name="templateType" id="templateType" />
        <input type="hidden" name="templateId" id="templateId" />
        <input type="hidden" name="fileId" id="fileId" />
        <input type="hidden" name="parentId" id="parentId" v-if="form.parentId" />
        <h3 style="text-align: center">
          {{
            copyTemplateId
            ? "复制报告模板"
            : templateId
              ? "编辑报告模板"
              : "新增报告模板"
          }}
        </h3>
        <el-form :model="form" label-width="85" :rules="rules" ref="templateRef">
          <el-form-item label="上级模板：">
            <el-tree-select v-model="form.parentId" clearable :data="templateOptions" :props="{
              value: 'templateId',
              label: 'templateName',
              children: 'children',
            }" value-key="templateId" placeholder="选择上级模板" check-strictly />
          </el-form-item>
          <el-form-item label="模板编号：" prop="templateCode">
            <el-input v-model.trim="form.templateCode"></el-input> </el-form-item><el-form-item label="模板名称："
            prop="templateName">
            <el-input v-model.trim="form.templateName"></el-input>
          </el-form-item>
          <el-form-item label="模板类型：" prop="templateType" v-if="!form.parentId">
            <el-select v-model="form.templateType" style="width: 100%" placeholder="请选择模板类型" clearable>
              <el-option v-for="dict in report_template" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-row style="justify-content: center">
          <el-button @click="Save" type="success">保存</el-button>
          <el-button @click="cancel" type="danger">取消</el-button>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
import {
  newFile,
  viewForm,
  openFile,
  getTemplateList,
} from "@/api/index/index";

const search = window.location.search;

const poHtmlCode = ref("");
const height = ref("");
const form = ref({});
const templateId = ref("");
const copyTemplateId = ref("");
const templateOptions = ref([]);

const rules = ref({
  templateCode: [
    { required: true, message: "模板编号不能为空", trigger: "blur" },
  ],
  templateName: [
    { required: true, message: "模板名称不能为空", trigger: "blur" },
  ],
  templateType: [
    { required: true, message: "模板类型不能为空", trigger: "blur" },
  ],
});

const { proxy } = getCurrentInstance();
const { report_template } = proxy.useShareDict("report_template");

getTemplateList().then((res) => {
  templateOptions.value = proxy.handleTree(res.data, "templateId");
});

if (search) {
  const searchList = search.substring(1).split(":");
  var value1 = searchList[1];
  form.value.parentId = value1;
  if (searchList[0] != "templateId1") {
    if (searchList[0] == "copyTemplateId") {
      copyTemplateId.value = value1;
    } else {
      templateId.value = value1;
    }
    // openFile({ templateId: value1 }).then((res) => {
    //   poHtmlCode.value = res;
    // });
    viewForm(value1).then((res) => {
      poHtmlCode.value = res.data.poHtmlCode;
      delete res.data.poHtmlCode;
      form.value = res.data;
      if (copyTemplateId.value) {
        delete form.value.templateId;
      }
    });
  } else {
    newFile().then((res) => {
      poHtmlCode.value = res;
    });
  }
} else {
  newFile().then((res) => {
    poHtmlCode.value = res;
  });
}

function ShowDefineDataRegions() {
  var drDefinedJson = pageofficectrl.word.DataRegionsDefinedAsJson;
  pageofficectrl.ShowHtmlModelessDialog("DataTagDlg", drDefinedJson, "left=300px;top=390px;width=700px;height=410px;frame:no;");
}

function OnPageOfficeCtrlInit() {
  // PageOffice的初始化事件回调函数，您可以在这里添加自定义按钮
  pageofficectrl.AddCustomToolButton("定义数据区域", "ShowDefineDataRegions", 10);
}
function AfterDocumentOpened() {
  // PageOffice的文档打开后事件回调函数
  pageofficectrl.DisableSave = true;
}
function BeforeDocumentSaved() {
  // PageOffice的文档保存前事件回调函数
}
function AfterDocumentSaved() {
  // PageOffice的文档保存后事件回调函数
  if (pageofficectrl.CustomSaveResult == "ok") {
    alert("保存成功！");
    var sResult = window.external.CallParentFunc("getList()");
    if (sResult !== "poerror:parentlost") {
      window.external.CallParentFunc("getList()");
    }
    // window.external.close();
  } else {
    alert("保存失败！");
  }
}

function recursion(options) {
  let isOk = false
  for (const item of options) {
    if (item.templateId == templateId.value) {
      isOk = recursion1(item.children)
      break
    } else {
      if (!item.children) {
        continue
      }
      isOk = recursion(item.children);
      if (isOk) {
        break;
      }
    }
  }
  return isOk
}

function recursion1(list) {
  if (!list) return false
  let isOk = false
  for (const row of list) {
    if (row.templateId == form.value.parentId) {
      isOk = true;
      break
    } else {
      if (!row.children) {
        continue
      }
      isOk = recursion1(row.children);
    }
  }
  return isOk
}

function Save() {
  proxy.$refs["templateRef"].validate((valid) => {
    if (valid) {
      const searchList = search.substring(1).split(":");
      if (searchList[0] == 'templateId') {
        if (form.value.parentId === searchList[1]) {
          alert('上级模板不能选择自己')
          return
        }
        if (recursion(templateOptions.value)) {
          alert('不能选取本模板下的子节点作为上级模板')
          return
        }
      }
      document.getElementById("templateCode").value = form.value.templateCode;
      document.getElementById("templateName").value = form.value.templateName;
      if (form.value.parentId) {
        delete form.value.templateType;
        document.getElementById("parentId").value = form.value.parentId;
      } else {
        document.getElementById("templateType").value = form.value.templateType;
      }
      if (form.value.templateId) {
        document.getElementById("templateId").value = form.value.templateId;
      }
      if (form.value.fileId) {
        document.getElementById("fileId").value = form.value.fileId;
      }
      pageofficectrl.WebSave();
    }
  });
}

function cancel() {
  window.external.close();
}

onMounted(() => {
  window.Save = Save;
  window.ShowDefineDataRegions = ShowDefineDataRegions;
  // 以下的为PageOffice事件的回调函数，名称不能改，否则PageOffice控件调用不到
  window.OnPageOfficeCtrlInit = OnPageOfficeCtrlInit;
  window.AfterDocumentOpened = AfterDocumentOpened;
  window.BeforeDocumentSaved = BeforeDocumentSaved;
  window.AfterDocumentSaved = AfterDocumentSaved;
  var box = document.querySelector(".app-container"); // 根据你的盒子ID选择器进行修改
  var boxDistanceFromTop = box.getBoundingClientRect().top; // 盒子距离顶部的距离
  height.value = window.innerHeight - boxDistanceFromTop - 21; // 视窗口高度减去盒子距离顶部的距离
});
</script>

<style scoped lang="scss"></style>
